#include "timeout.h"

#ifdef __cpluscplus    
#else
    static void _user_onTimeout(uint32_t times) {};
#endif

Timeout::Timeout(unsigned long (*now)()):Timeout(now, 0)
{
}
Timeout::Timeout(unsigned long (*now)(), uint32_t timeout)
{
    setTimeout(timeout);
#ifdef __cpluscplus
    onTimeout([](uint32_t times){});    // 设置一个默认实现，防止指针空
#else
    onTimeout(_user_onTimeout);             // 设置一个默认实现，防止指针空
#endif

    user_now = now;
}

void Timeout::start()
{
    if (!isRunning()) {
        _start = user_now();
    }
}

void Timeout::restart()
{
    if (isRunning()) {
        _start = user_now();
    }
}

bool Timeout::isRunning() 
{
    return _start > 0;
}

void Timeout::stop()
{
    _start = 0;
    _times = 0;
}

void Timeout::setTimeout(uint32_t timeout)
{
    _timeout = timeout;
}

bool Timeout::isTimeout()
{
    return isTimeout(_timeout);
}

bool Timeout::isTimeout(uint32_t timeout)
{
    if (isRunning()) 
    {
        unsigned long now = user_now();
        // inf << "now " << now << " timeout " << timeout << " start " << _start << endl;
        // uint32_t t = _start + timeout;
        unsigned long t = now - _start;
        // return now > _start + timeout;
        if (t > timeout) {
            // inf << "now " << now << " timeout " << timeout << " start " << _start << endl;
            if (_times == 0) {
                _times = t;
            }
            return true;
        }
    }
    return false;
}

void Timeout::onTimeout(void (*function)(uint32_t times))
{
    this->user_onTimeout = function;
}

void Timeout::dispatchTimeoutEvent()
{
    user_onTimeout(_times);
}